import React from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import {Form, Input, Button, message, Row, Col, Select} from 'antd';
const Option = Select.Option;
const FormItem = Form.Item;
import ImgArea from 'components/Form/img-area';
import actions from '../../store/actions/game-box';
import EditableTagGroup from './tags';
import styles from './editor.scss';
@Form.create()
class Editor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      coverUrl: false,
      iconUrl: false,
      name: '',
      desc: '',
      status: 0,
      gameType: 1,
      qrCode: false,
      combineQrCode: false,
      tags: []
    };
  }

  async componentDidMount() {
    if (this.props.location.data) {
      const {dispatch} = this.props;
      let {data} = this.props.location;
      let {id, type} = data;
      if (id && type === 'edit') {
        const res = await dispatch(actions.queryById(id));
        if (res.code === '0') {
          const {
            cover,
            discript,
            icon,
            link,
            name,
            seq,
            slogan,
            status,
            tags,
            gameType,
            submitter,
            submitterMobile,
            submitterEmail,
            qrCode,
            combineQrCode
          } = res.data;
          this.props.form.setFieldsValue({
            name,
            desc: discript,
            slogan,
            link,
            seq,
            submitter,
            submitterMobile,
            submitterEmail
          });
          this.setState({
            coverUrl: cover,
            iconUrl: icon,
            qrCode,
            combineQrCode,
            tags: tags ? tags.split(',') : [],
            status,
            gameType
          });
        }
      }
    }
  }

  onCoverChange(url) {
    this.setState({
      coverUrl: url
    });
  }

  onTagsChange(tags) {
    this.setState({
      tags
    });
  }

  onIconChange(url) {
    this.setState({
      iconUrl: url
    });
  }

  onStatusChange(status) {
    this.setState({
      status
    });
  }

  onGameTypeChange(type) {
    this.setState({
      gameType: type
    });
  }

  onQrCodeChange(url) {
    this.setState({
      qrCode: url
    });
  }

  onCombineQrCodeChange(url) {
    this.setState({
      combineQrCode: url
    });
  }

  addItem() {
    this.props.form.validateFields(async (error, values) => {
      if (!error) {
        let {name, desc, slogan, link, seq = 0, submitter, submitterEmail, submitterMobile} = values;
        const {dispatch} = this.props;
        const params = {
          name,
          discript: desc,
          slogan,
          link,
          seq: seq || 1,
          tags: this.state.tags.join(','),
          status: this.state.status,
          cover: this.state.coverUrl,
          submitter,
          submitterEmail,
          submitterMobile,
          gameType: this.state.gameType
        };
        if (this.state.iconUrl) {
          params.icon = this.state.iconUrl;
        }
        if (this.state.coverUrl) {
          params.cover = this.state.coverUrl;
        }
        if (this.state.qrCode) {
          params.qrCode = this.state.qrCode;
        }
        if (this.state.combineQrCode) {
          params.combineQrCode = this.state.combineQrCode;
        }
        const res = await dispatch(actions.addGame(params));
        if (res.code === '0') {
          message.info('添加成功！');
          this.props.history.goBack();
        }
      }
    });
  }

  editItem() {
    this.props.form.validateFields(async (error, values) => {
      if (!error) {
        let {name, desc, slogan, link, seq = 0, submitter, submitterEmail, submitterMobile} = values;
        const {dispatch} = this.props;
        let {data} = this.props.location;
        const params = {
          name,
          discript: desc,
          slogan,
          link,
          seq: seq || 1,
          tags: this.state.tags.join(','),
          status: this.state.status,
          icon: this.state.iconUrl,
          cover: this.state.coverUrl,
          submitter,
          submitterMobile,
          submitterEmail
        };
        if (this.state.iconUrl) {
          params.icon = this.state.iconUrl;
        }
        if (this.state.coverUrl) {
          params.cover = this.state.coverUrl;
        }
        if (this.state.qrCode) {
          params.qrCode = this.state.qrCode;
        }
        if (this.state.combineQrCode) {
          params.combineQrCode = this.state.combineQrCode;
        }
        const res = await dispatch(actions.editGame(data.id, params));
        if (res.code === '0') {
          message.info('修改成功！');
          this.props.history.goBack();
        }
      }
    });
  }

  goCombine() {
    this.props.form.validateFields(async (error, values) => {
      const {name} = values;
      if (!name || name === '') {
        message.error('请先填写游戏名');
        return;
      }
      const iconUrl = this.state.iconUrl;
      if (!iconUrl) {
        message.error('请先上传游戏小图标');
        return;
      }
      const qrCode = this.state.qrCode;
      if (!qrCode) {
        message.error('请先上传小程序码');
        return;
      }
      const url = `/combine?name=${name}&icon=${iconUrl}&qrCode=${qrCode}&tags=${this.state.tags.join('.')}`;
      window.open(url, 'combine');
    });
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          <Row>
            <Col span={11}>
              <FormItem label="游戏名称">
                {getFieldDecorator('name', {
                  rules: [
                    {
                      required: true,
                      message: 'Please input your game name'
                    }
                  ]
                })(<Input />)}
              </FormItem>
            </Col>
            <Col span={11} style={{float: 'right'}}>
              <FormItem label="游戏描述">
                {getFieldDecorator('desc', {
                  rules: [
                    {
                      required: true,
                      message: 'Please input your desc!'
                    }
                  ]
                })(<Input />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={11}>
              <FormItem label="游戏口号">
                {getFieldDecorator('slogan', {
                  rules: [
                    {
                      required: true,
                      message: 'Please input your slogan!'
                    }
                  ]
                })(<Input />)}
              </FormItem>
            </Col>
            <Col span={11} style={{float: 'right'}}>
              <FormItem label="游戏链接">
                {getFieldDecorator('link', {
                  rules: [
                    {
                      required: true,
                      message: 'Please input your link!'
                    }
                  ]
                })(<Input type="url" />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={11}>
              <FormItem label="优先级">
                {getFieldDecorator('seq', {
                  rules: [
                    {
                      required: false
                    }
                  ]
                })(<Input type="number" />)}
              </FormItem>
            </Col>
            <Col span={11} style={{float: 'right'}}>
              <FormItem label="发布状态">
                <Select value={this.state.status} onChange={(e) => this.onStatusChange(e)}>
                  <Option value={0}>暂不发布</Option>
                  <Option value={1}>直接发布</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={11}>
              <FormItem label="发布类型">
                <Select value={this.state.gameType} onChange={(e) => this.onGameTypeChange(e)}>
                  <Option value={1}>自营游戏</Option>
                  <Option value={2}>第三方游戏</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span={11} style={{float: 'right'}}>
              <FormItem label="发布者姓名">
                {getFieldDecorator('submitter', {
                  rules: [
                    {
                      required: false,
                      message: '请输入发布者姓名'
                    }
                  ]
                })(<Input />)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={11}>
              <FormItem label="发布者手机号">
                {getFieldDecorator('submitterMobile', {
                  rules: [
                    {
                      required: false,
                      message: '请输入发布者手机号'
                    }
                  ]
                })(<Input type="tel" />)}
              </FormItem>
            </Col>
            <Col span={11} style={{float: 'right'}}>
              <FormItem label="发布者邮箱">
                {getFieldDecorator('submitterEmail', {
                  rules: [
                    {
                      required: false,
                      message: '请输入发布者邮箱'
                    }
                  ]
                })(<Input type="email" />)}
              </FormItem>
            </Col>
          </Row>
          <FormItem label="标签">
            <EditableTagGroup tags={this.state.tags} onTagsChange={(tags) => this.onTagsChange(tags)} />
          </FormItem>
          <FormItem>
            <ImgArea
              label="封面图片:"
              btnId="coverUrl"
              imgUrl={this.state.coverUrl}
              onChange={(url) => {
                this.onCoverChange(url);
              }}
            />
          </FormItem>
          <FormItem>
            <ImgArea
              label="小图标:"
              imgUrl={this.state.iconUrl}
              btnId="iconUrl"
              onChange={(url) => {
                this.onIconChange(url);
              }}
            />
          </FormItem>
          <FormItem>
            <ImgArea
              label="小程序码:"
              imgUrl={this.state.qrCode}
              btnId="qrCode"
              onChange={(url) => {
                this.onQrCodeChange(url);
              }}
            />
          </FormItem>
          <FormItem>
            <div className={styles.mqrWrap}>
              <ImgArea
                label="营销小程序码:"
                imgUrl={this.state.combineQrCode}
                btnId="combineQrCode"
                onChange={(url) => {
                  this.onCombineQrCodeChange(url);
                }}
              />
              <Button
                type="primary"
                onClick={() => {
                  this.goCombine();
                }}
                className={styles.combine}
              >
                去合成
              </Button>
            </div>
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              onClick={() => {
                let {data = {}} = this.props.location;
                let {id, type} = data;
                if (id && type === 'edit') {
                  this.editItem();
                } else {
                  this.addItem();
                }
              }}
            >
              提交
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}
function select(state) {
  return state;
}
export default withRouter(connect(select)(Editor));
